#include "sensor_read.h"
#include "tftp_server.h"
#include "eeprom.h"
#include "app.h"
#include "wdg.h"
#include "app_3axis_output.h"

#define STRING_TO_HEX(x) (x - 0x30)

extern uint32_t record_pointer;
extern lis2dh12_param_t sensor_param_data ;
uint16_t record_cache_read_number = 0;

static uint32_t record_cache_get_read_address(uint16_t n)
{
    uint32_t read_address = 0;
    
    read_address = EEPROM_DATA_BEGIN_ADDR + (((EEPROM_DATA_RECORD_SIZE + record_pointer - (1 + n)) % EEPROM_DATA_RECORD_SIZE)  * APP_SNESOR_RECORD_WORD_LEN * 4) % EEPROM_DATA_SIZE;
    return read_address;
}

static void record_cache_read_by_word(uint32_t* buffer, uint32_t address)
{
    uint32_t i = 0;
 
    for(i = 0; i < APP_SNESOR_RECORD_WORD_LEN; i++)
        buffer[i] = eeprom_read_word(address + (i * 4));
}

static void record_cache_read_one_record(uint32_t* buffer, uint16_t n)
{
    uint32_t read_address = 0;
 
    read_address = record_cache_get_read_address(n);
    
    record_cache_read_by_word(buffer, read_address);
}

static void read_time_stamp_voltage(uint32_t* buffer)
{
    uint16_t i = 0;
 
    for( i = 0; i < APP_SNESOR_RECORD_WORD_LEN; i++)
        buffer[i] = eeprom_read_word(EEPROM_TIME_STAMP_VOLTAGE_VALUE_ADD + (i * 4));
}

uint16_t record_cache_read_by_number(uint8_t blk, uint8_t* buffer)
{
    uint16_t i = 0;
    uint32_t* p = (void*)buffer;
    
    read_time_stamp_voltage(p);
    
    for(i = 0; i < record_cache_read_number; i++)
        record_cache_read_one_record(&p[(i + 1) * APP_SNESOR_RECORD_WORD_LEN], i);
 
    return (i * APP_SNESOR_RECORD_WORD_LEN * 4);
 
}

static void record_cache_get_number_of_record_reading(char* data)
{
    
    record_cache_read_number = (STRING_TO_HEX(data[0]) * 10 + STRING_TO_HEX(data[1])) % EEPROM_DATA_RECORD_SIZE;
    if(record_cache_read_number > 29)
        record_cache_read_number  = 29;
   
}

bool _sensor_read_cmd_open(char* name, uint8_t mode)
{   
    static char tmp_buf[12] = {0,0,0,0,0,0,0,0,0,0,0,0};
 
    memcpy(tmp_buf, name, 11);
 
    if (0 == strcmp(tmp_buf, "sensor.read")) {

        record_cache_get_number_of_record_reading(&name[12]);
        return true;
    } else {
        return false;
    }
}

uint16_t (_sensor_read_cmd_read)(uint8_t blk, uint8_t* buffer)
{
    if (blk >= 1) {
        return record_cache_read_by_number(blk, buffer);
    }else{
        return 0;
    }
}

void (_sensor_read_cmd_write)(uint8_t blk, uint8_t* buffer, uint16_t len)
{
     
}

void (_sensor_read_cmd_close)(void)
{

}

const tftp_server_plugin_t tftp_server_plugin_sensor_read_cmd = {
    _sensor_read_cmd_open,
    _sensor_read_cmd_read,
    _sensor_read_cmd_write,
    _sensor_read_cmd_close,
};



